package in.muton.edushare.poll.questions;

import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.poll.panels.IPollPanelContainer;
import in.muton.edushare.poll.sections.PollSectionEdit;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.Radio;
import org.apache.wicket.markup.html.form.RadioGroup;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.PollsDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.PollOptions;
import com.edushare.common.vo.PollPages;
import com.edushare.common.vo.PollQuestions;

public class NewQuestion extends EdusharePanel {
	private static final Log log = LogFactory.getLog(NewQuestion.class);

	public NewQuestion(String id, IModel<Poll> model1,
			IModel<PollQuestions> model2, EduShareBasePage page) {
		super(id, model1, page);
		questionModel = model2;
		pollModel = model1;
		this.pollPage = new CayenneModel<PollPages>(questionModel.getObject()
				.getPage());
		newQuestion = false;
		questionType = questionModel.getObject().getQuestionType();
		setQuestionFreeForm(questionModel.getObject().getQuestion());
		setQuestionMCQ(questionModel.getObject().getQuestion());
		setQuestionRating(questionModel.getObject().getQuestion());

		List<PollOptions> optionList = model2.getObject().getOptions();
		for (PollOptions o : optionList) {
			answerOptions += o.getOptionString() + "\n";
		}
		init(questionModel.getObject().getQuestionSerialNo());
	}

	public NewQuestion(String id, IModel<Poll> model, EduShareBasePage page,
			IModel<PollPages> pollPage) {
		super(id, model, page);
		this.pollModel = model;
		this.pollPage = pollPage;
		questionType = new Integer(0);
		log.debug("Single model, no question");
		log.debug("Poll id = " + model.getObject().getPollId());
		add(JavascriptPackageResource.getHeaderContribution(NewQuestion.class,
				"questions.js"));
		init(PollSectionEdit.getMaxQuestionNum(pollPage.getObject()) + 1);
	}

	private void init(final int sNo) {
		add(JavascriptPackageResource.getHeaderContribution(NewQuestion.class,
				"questions.js"));
		Form<Void> f = new Form<Void>("newQuestion");
		add(f);
		RadioGroup<Integer> radioGroup = new RadioGroup<Integer>(
				"questionTypeGroup", new PropertyModel<Integer>(this,
						"questionType"));
		f.add(radioGroup);
		radioGroup.add(new Radio<Integer>("mcso", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_SINGLE_CHOICE)));
		radioGroup.add(new Radio<Integer>("mcmo", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_MULTIPLE_CHOICE)));
		radioGroup.add(new Radio<Integer>("free", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_DESCRIBE)));
		radioGroup.add(new Radio<Integer>("rating", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_RATING)));
		radioGroup.add(new Radio<Integer>("preferences", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_PREFERENCES)));
		radioGroup.add(new Radio<Integer>("shortText", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_SHORT_TEXT)));
		radioGroup.add(new Radio<Integer>("dropDown", new Model<Integer>(
				PollQuestions.QUESTION_TYPE_DROPDOWN)));

		f.add(new CheckBox("required", new PropertyModel<Boolean>(this,
				"required")));

		setDefaultModel(new CompoundPropertyModel<NewQuestion>(this));
		f.add(new TextArea<String>("questionMCQ"));
		f.add(new TextArea<String>("questionFreeForm"));
		f.add(new TextArea<String>("questionRating"));
		f.add(new TextArea<String>("answerOptions"));
		f.add(new Label("title", new Model<String>() {
			private static final long serialVersionUID = -4063024478794246193L;

			@Override
			public String getObject() {
				if (questionModel == null)
					return "Add question "
							+ (pollModel.getObject().getQuestions().size() + 1);
				else
					return "Edit question "
							+ questionModel.getObject().getQuestionSerialNo();
			}
		}));

		f.add(new Button("add") {
			private static final long serialVersionUID = 1090362529774674344L;

			@Override
			public void onSubmit() {
				log.debug("Submit for form");
				if (!submit(sNo))
					return;
				/*
				 * PageParameters params = new PageParameters(); params.add("0",
				 * pollModel.getObject().getPollId().toString());
				 * setResponsePage(PollEdit.class, params);
				 */
			}
		});
	}

	private boolean submit(int sNo) {
		log.debug("In form submit");
		PollsDAO pDao = new PollsDAO(getORMInterface());
		PollQuestions pQ = null;
		if (!newQuestion) {
			pDao.deleteQuestion(questionModel.getObject());
			questionModel = null;
		}
		if (questionType == null) {
			setError("Please choose a question type.");
			return false;
		}
		log.debug("In form submit: Question type = " + questionType);
		switch (questionType.intValue()) {
		case (PollQuestions.QUESTION_TYPE_SINGLE_CHOICE):
		case (PollQuestions.QUESTION_TYPE_MULTIPLE_CHOICE):
		case (PollQuestions.QUESTION_TYPE_DROPDOWN):
		case (PollQuestions.QUESTION_TYPE_PREFERENCES):
			if (!StringUtil.isValid(questionMCQ)) {
				setError("Please provide a question.");
				return false;
			}
			if (breakOptions().length == 0) {
				setError("Please provide options for the user to choose from.");
				return false;
			}
			log.debug("In form submit: MCQ/SCQ");
			pQ = pDao.addQuestionToPoll(pollModel.getObject(), questionMCQ,
					required, questionType, pollPage.getObject(), sNo);
			pDao.addMultipleOptionsToPoll(pQ, breakOptions());
			break;
		case (PollQuestions.QUESTION_TYPE_DESCRIBE):
		case (PollQuestions.QUESTION_TYPE_SHORT_TEXT):
			if (!StringUtil.isValid(questionFreeForm)) {
				setError("Please provide a question.");
				return false;
			}
			log.debug("In form submit: Describe");
			pQ = pDao.addQuestionToPoll(pollModel.getObject(),
					questionFreeForm, required, questionType, pollPage
							.getObject(), sNo);
			break;
		case (PollQuestions.QUESTION_TYPE_RATING):
			if (!StringUtil.isValid(questionRating)) {
				setError("Please provide a question.");
				return false;
			}
			log.debug("In form submit: Rating");
			pQ = pDao.addQuestionToPoll(pollModel.getObject(), questionRating,
					required, questionType, pollPage.getObject(), sNo);
			break;
		default:
			return false;
		}
		questionRating = "";
		questionFreeForm = "";
		questionMCQ = "";
		answerOptions = "";
		return true;
	}

	private String[] breakOptions() {
		log.debug(answerOptions);
		if (answerOptions == null) {
			return new String[0];
		}

		String[] options = answerOptions.split("\n");
		ArrayList<String> list = new ArrayList<String>();
		for (String o : options) {
			if (StringUtil.isValid(o.replace("\r", "").trim()))
				list.add(o.replace("\r", "").trim());
		}

		return (String[]) list.toArray(new String[list.size()]);
	}

	private String questionRating = "";
	private String questionFreeForm = "";
	private String questionMCQ = "";
	private String answerOptions = "";
	private int required = PollQuestions.ANSWER_OPTIONAL;
	private Integer questionType = PollQuestions.QUESTION_TYPE_SINGLE_CHOICE;
	private IModel<Poll> pollModel = null;
	private IModel<PollQuestions> questionModel = null;
	private IModel<PollPages> pollPage;
	private boolean newQuestion = true;
	private IPollPanelContainer container = null;

	private static final long serialVersionUID = -321825250755647903L;

	public String getQuestionRating() {
		return questionRating;
	}

	public void setQuestionRating(String questionRating) {
		this.questionRating = questionRating;
	}

	public String getQuestionFreeForm() {
		return questionFreeForm;
	}

	public void setQuestionFreeForm(String questionFreeForm) {
		this.questionFreeForm = questionFreeForm;
	}

	public String getQuestionMCQ() {
		return questionMCQ;
	}

	public void setQuestionMCQ(String questionMCQ) {
		this.questionMCQ = questionMCQ;
	}

	public String getAnswerOptions() {
		return answerOptions;
	}

	public void setAnswerOptions(String answerOptions) {
		this.answerOptions = answerOptions;
	}

	public void setQuestionType(Integer questionType) {
		this.questionType = questionType;
	}

	public Integer getQuestionType() {
		return questionType;
	}

	public void setRequired(boolean required) {
		if (required)
			this.required = PollQuestions.ANSWER_REQUIRED;
		else
			this.required = PollQuestions.ANSWER_OPTIONAL;
	}

	public boolean getRequired() {
		return required == PollQuestions.ANSWER_REQUIRED;
	}
}
